package com.zensun.web.controller.system;

import com.zensun.common.annotation.Log;
import com.zensun.common.core.controller.BaseController;
import com.zensun.common.core.domain.BaseEntity;
import com.zensun.common.core.domain.R;
import com.zensun.common.core.page.PageDataInfo;
import com.zensun.common.enums.BusinessType;
import com.zensun.system.domain.SysUser;
import com.zensun.system.domain.UpdateUserStatus;
import com.zensun.system.domain.dto.SysUserDto;
import com.zensun.system.domain.dto.SysUserPatchDto;
import com.zensun.system.domain.vo.SysUserDetailVo;
import com.zensun.system.domain.vo.SysUserVo;
import com.zensun.system.service.ISysDeptService;
import com.zensun.system.service.ISysUserService;
import com.zensun.system.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author gmk
 */
@Api(value = "管理员配置管理", tags = "管理员配置模块")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取用户列表
     */
    @ApiOperation("查询管理员列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public R<PageDataInfo<SysUserVo>> list(SysUserDto userDto) {
        startPage();
        List<SysUserVo> list = userService.selectUserList(userDto);
        PageDataInfo pageDataTable = getPageDataTable(list);
        //构建isSelf字段
        List<SysUserVo> stream = pageDataTable.getList();
        //查询所有部门
        Map<Long, Integer> deptMap = deptService.list().stream().collect(HashMap::new, (map, p) -> map.put(p.getDeptId(), p.getLevel()), HashMap::putAll);
        //查询所有员工
        Map<Long, Long> userMap = userService.list().stream().collect(HashMap::new, (map, p) -> map.put(p.getUserId(), p.getDeptId()), HashMap::putAll);
        List<SysUserVo> result = stream.stream().map(sysUserVo -> {
            //isSelf 为true  前端页面不能编辑
            //只能编辑自己创建的  并且不能修改自己
            //当前登录部门的级别要大于数据的创建人的部门级别 才可以修改 自己创建的 自己可以修改
            Integer level = deptMap.get(userMap.get(sysUserVo.getUpdateBy()));
            boolean flag = true;
            if (sysUserVo.getUpdateBy().equals(SecurityUtils.getLoginUser().getUser().getUserId()) && !SecurityUtils.isAdmin(sysUserVo.getUserId())) {
                flag = false;
            } else if (SecurityUtils.getLoginUser().getUser().getDept().getLevel() < level) {
                flag = false;
            }
            sysUserVo.setIsSelf(flag);
            return sysUserVo;
        }).collect(Collectors.toList());
        pageDataTable.setList(result);
        return R.success(pageDataTable);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户ID获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/{userId}")
    public R<SysUserDetailVo> getInfo(@ApiParam("用户Id") @PathVariable("userId") Long userId) {
        return R.success(userService.selectUserById(userId));
    }

    /**
     * 新增管理员之前的校验接口
     */
    @ApiOperation("新增管理员之前的校验接口")
    @GetMapping("/addVerify")
    public R addVerify(@RequestParam String telePhone) {
        return R.success(userService.addVerify(telePhone));
    }


    /**
     * 新增用户
     */
    @ApiOperation("新增管理员")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated(BaseEntity.AddGrop.class) @RequestBody SysUser user) {
        return R.toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改管理员")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated(BaseEntity.UpdateGrop.class) @RequestBody SysUser user) {
        return R.toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除管理员")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@ApiParam("ID集合（1,2）") @PathVariable Long[] userIds) {
        return R.toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PatchMapping("/resetPwd")
    public R resetPwd(@RequestBody SysUserPatchDto sysUserPatchDto) {
        return R.toAjax(userService.resetPwd(sysUserPatchDto));
    }

    /**
     * 冻结账户
     */
    @ApiOperation("冻结账户")
    @PreAuthorize("@ss.hasPermi('system:user:block')")
    @Log(title = "用户基本信息", businessType = BusinessType.UPDATE)
    @PatchMapping("/blockedAccount")
    public R blockedAccount(@Validated @RequestBody UpdateUserStatus memberStatus) {
        return R.toAjax(userService.blockedAccount(memberStatus));
    }

    /**
     * 解冻账户
     */
    @ApiOperation("解冻账户")
    @PreAuthorize("@ss.hasPermi('system:user:dredge')")
    @Log(title = "用户基本信息", businessType = BusinessType.UPDATE)
    @PatchMapping("/dredgeAccount")
    public R dredgeAccount(@Validated @RequestBody UpdateUserStatus memberStatus) {
        return R.toAjax(userService.dredgeAccount(memberStatus));
    }
}
